const express=require('express');
const router=express.Router();
const mongoose =require("mongoose");

const InWareHouseBill=require("../../models/InWareHouseBill");
const BilletWarehouse=require("../../models/BilletWarehouse");
const BilletedWarehouse=require("../../models/BilletedWarehouse");
const Variety=require("../../models/Variety");
const SaleBill = require('../../models/SaleBill');
const ReturnedBill = require('../../models/ReturnedBill');
const ProcessBill = require("../../models/processBill.js");
const ProcessReturnBill = require("../../models/processReturnBill");

router.post("/inBillet/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
    }
    BilletWarehouse.find({})
    .then(billetWarehouse=>{
        data.warehouse = billetWarehouse.map(v=>v.name);
        Variety.find({})
        .then(goods=>{
            for(let i=0;i<goods.length;i++){
                data.goods.push(goods[i].name);
                data.goodsNumber[goods[i].name] = goods[i].number
            }
            res.json(data);
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
    
})


router.post("/inBillet/getList",(req,res)=>{
    let query = JSON.parse(req.query.query);
    const limit=Number(query.limit);
    const page=Number(query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(query[i]);
            dateflag = true;
        }
    }
    if(query['warehouse'] != undefined){
            if(dateflag) match['date'] = datelimit;
            let groupWord = {};
            req.query.method = JSON.parse(req.query.method);
            for(let i in req.query.method.checkList){
                if(req.query.method.checkList[i] == "按照仓库统计"){
                    groupWord.warehouse = "$warehouse";
                }
                else if (req.query.method.checkList[i] == "按照产品名称统计"){
                    groupWord.name = "$name";
                }
                else if (req.query.method.checkList[i] == "按照产品号码统计"){
                    groupWord.number = "$number";
                }
            }
            InWareHouseBill.aggregate([{$match:match},
                {
                    $group:{_id:groupWord, 
                    piece:{$sum:'$piece'},
                    length:{$sum:'$length'},
                    }
                }])
            .exec((error, bills)=>{
                const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
                ProcessBill.aggregate([{$match:match},
                    {
                        $group:{_id:groupWord, 
                        piece:{$sum:'$outPiece'},
                        length:{$sum:'$outLength'},
                        }
                    }])
                .exec((error, pbills)=>{
                    let obj_1 = {};
                    let obj_2 = {};
                    for(let i in pageList){
                        let key = JSON.stringify(pageList[i]._id);
                        obj_1[key] = pageList[i];
                    }
                    for(let i in pbills){
                        let key = JSON.stringify(pbills[i]._id);
                        obj_2[key] = pbills[i];
                    }
                    
                    for(let i in obj_1){
                        if(obj_2[i] != undefined){
                            obj_1[i].piece -= obj_2[i].piece;
                            obj_1[i].length -= obj_2[i].length;
                        }
                    }
                    let pageList_ = [];
                    for(let i in obj_1){
                        pageList_.push(obj_1[i]);
                    }
                    res.json({
                        code:200,
                        list:pageList_,
                        total:bills.length
                    });
                })
            })
    }
    else{
        BilletWarehouse.find({})
        .then(billetWarehouse=>{
            let warehouse = billetWarehouse.map(v=>v.name);
            match.warehouse = {$in: warehouse};
            if(dateflag) match['date'] = datelimit;
            let groupWord = {};
            req.query.method = JSON.parse(req.query.method);
            for(let i in req.query.method.checkList){
                if(req.query.method.checkList[i] == "按照仓库统计"){
                    groupWord.warehouse = "$warehouse";
                }
                else if (req.query.method.checkList[i] == "按照产品名称统计"){
                    groupWord.name = "$name";
                }
                else if (req.query.method.checkList[i] == "按照产品号码统计"){
                    groupWord.number = "$number";
                }
            }
            InWareHouseBill.aggregate([{$match:match},
                {
                    $group:{_id:groupWord, 
                    piece:{$sum:'$piece'},
                    length:{$sum:'$length'},
                    }
                }])
            .exec((error, bills)=>{
                const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
                ProcessBill.aggregate([{$match:match},
                    {
                        $group:{_id:groupWord, 
                        piece:{$sum:'$outPiece'},
                        length:{$sum:'$outLength'},
                        }
                    }])
                .exec((error, pbills)=>{
                    let obj_1 = {};
                    let obj_2 = {};
                    for(let i in pageList){
                        let key = JSON.stringify(pageList[i]._id);
                        obj_1[key] = pageList[i];
                    }
                    for(let i in pbills){
                        let key = JSON.stringify(pbills[i]._id);
                        obj_2[key] = pbills[i];
                    }
                    
                    for(let i in obj_1){
                        if(obj_2[i] != undefined){
                            obj_1[i].piece -= obj_2[i].piece;
                            obj_1[i].length -= obj_2[i].length;
                        }
                    }
                    let pageList_ = [];
                    for(let i in obj_1){
                        pageList_.push(obj_1[i]);
                    }
                    res.json({
                        code:200,
                        list:pageList_,
                        total:bills.length
                    });
                })
            })
           
        })
    }
    
})


router.post("/inBilleted/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
    }
    BilletedWarehouse.find({})
    .then(billetWarehouse=>{
        data.warehouse = billetWarehouse.map(v=>v.name);
        Variety.find({})
        .then(goods=>{
            for(let i=0;i<goods.length;i++){
                data.goods.push(goods[i].name);
                data.goodsNumber[goods[i].name] = goods[i].number
            }
            res.json(data);
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
    
})


router.post("/inBilleted/getList",(req,res)=>{
    let query = JSON.parse(req.query.query);
    const limit=Number(query.limit);
    const page=Number(query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(query[i]);
            dateflag = true;
        }
    }
    if(query['warehouse'] != undefined){
        if(dateflag) match['date'] = datelimit;
        let groupWord = {};
        req.query.method = JSON.parse(req.query.method);
        for(let i in req.query.method.checkList){
            if(req.query.method.checkList[i] == "按照仓库统计"){
                groupWord.warehouse = "$warehouse";
            }
            else if (req.query.method.checkList[i] == "按照产品名称统计"){
                groupWord.name = "$name";
            }
            else if (req.query.method.checkList[i] == "按照产品号码统计"){
                groupWord.number = "$number";
            }
        }
        ProcessReturnBill.aggregate([{$match:match},
            {
                $group:{_id:groupWord, 
                piece:{$sum:'$piece'},
                length:{$sum:'$length'},
                }
            }])
        .exec((error, bills)=>{
            const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
            SaleBill.aggregate([{$match:match},
                {
                    $group:{_id:groupWord, 
                    piece:{$sum:'$outPiece'},
                    length:{$sum:'$outLength'},
                    }
                }])
                .exec((error, pbills)=>{
                    ReturnedBill.aggregate([{$match:match},
                        {
                            $group:{_id:groupWord, 
                            piece:{$sum:'$inPiece'},
                            length:{$sum:'$inLength'},
                            }
                        }])
                    .exec((error, rbills)=>{
                        // console.log(rbills)
                        let obj_1 = {};
                        let obj_2 = {};
                        let obj_3 = {};
                        for(let i in pageList){
                            let key = JSON.stringify(pageList[i]._id);
                            obj_1[key] = pageList[i];
                        }
                        for(let i in pbills){
                            let key = JSON.stringify(pbills[i]._id);
                            obj_2[key] = pbills[i];
                        }
                        for(let i in rbills){
                            let key = JSON.stringify(rbills[i]._id);
                            obj_3[key] = rbills[i];
                        }
                        
                        for(let i in obj_1){
                            if(obj_2[i] != undefined){
                                obj_1[i].piece -= obj_2[i].piece;
                                obj_1[i].length -= obj_2[i].length;
                            }
                            if(obj_3[i] != undefined){
                                obj_1[i].piece += obj_3[i].piece;
                                obj_1[i].length += obj_3[i].length;
                                delete obj_3[i];
                            }
                        }
                        // console.log(obj_3)
                        for(let i in obj_3){
                            obj_1[i] = {};
                            obj_1[i]._id = obj_3[i]._id;
                            obj_1[i].piece = obj_3[i].piece;
                            obj_1[i].length = obj_3[i].length;
                        }
                        // console.log(obj_3)
                        let pageList_ = [];
                        for(let i in obj_1){
                            pageList_.push(obj_1[i]);
                        }
                        res.json({
                            code:200,
                            list:pageList_,
                            total:bills.length
                        });
                })

                    
            })
         })
           
    }
    else{
        BilletedWarehouse.find({})
        .then(billetedWarehouse=>{
            let warehouse = billetedWarehouse.map(v=>v.name);
            match.warehouse = {$in: warehouse};
            if(dateflag) match['date'] = datelimit;
            let groupWord = {};
            req.query.method = JSON.parse(req.query.method);
            for(let i in req.query.method.checkList){
                if(req.query.method.checkList[i] == "按照仓库统计"){
                    groupWord.warehouse = "$warehouse";
                }
                else if (req.query.method.checkList[i] == "按照产品名称统计"){
                    groupWord.name = "$name";
                }
                else if (req.query.method.checkList[i] == "按照产品号码统计"){
                    groupWord.number = "$number";
                }
            }
            ProcessReturnBill.aggregate([{$match:match},
                {
                    $group:{_id:groupWord, 
                    piece:{$sum:'$piece'},
                    length:{$sum:'$length'},
                    }
                }])
            .exec((error, bills)=>{
                const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
                SaleBill.aggregate([{$match:match},
                    {
                        $group:{_id:groupWord, 
                        piece:{$sum:'$outPiece'},
                        length:{$sum:'$outLength'},
                        }
                    }])
                    .exec((error, pbills)=>{
                        ReturnedBill.aggregate([{$match:match},
                            {
                                $group:{_id:groupWord, 
                                piece:{$sum:'$inPiece'},
                                length:{$sum:'$inLength'},
                                }
                            }])
                        .exec((error, rbills)=>{
                            // console.log(rbills)
                            let obj_1 = {};
                            let obj_2 = {};
                            let obj_3 = {};
                            for(let i in pageList){
                                let key = JSON.stringify(pageList[i]._id);
                                obj_1[key] = pageList[i];
                            }
                            for(let i in pbills){
                                let key = JSON.stringify(pbills[i]._id);
                                obj_2[key] = pbills[i];
                            }
                            for(let i in rbills){
                                let key = JSON.stringify(rbills[i]._id);
                                obj_3[key] = rbills[i];
                            }
                            
                            for(let i in obj_1){
                                if(obj_2[i] != undefined){
                                    obj_1[i].piece -= obj_2[i].piece;
                                    obj_1[i].length -= obj_2[i].length;
                                }
                                if(obj_3[i] != undefined){
                                    obj_1[i].piece += obj_3[i].piece;
                                    obj_1[i].length += obj_3[i].length;
                                    delete obj_3[i];
                                }
                            }
                            for(let i in obj_3){
                                obj_1[i] = {};
                                obj_1[i]._id = obj_3[i]._id;
                                obj_1[i].piece = obj_3[i].piece;
                                obj_1[i].length = obj_3[i].length;
                            }
                            let pageList_ = [];
                            for(let i in obj_1){
                                pageList_.push(obj_1[i]);
                            }
                            res.json({
                                code:200,
                                list:pageList_,
                                total:bills.length
                            });
                    })

                    
                })
            })
           
        })
    }
    
})


module.exports=router;